﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;
using Webdiyer.WebControls.Mvc;
using System.Data;
using System.IO;
using Newtonsoft.Json;
using ElingOA6_Admin_DSJCJ.Model;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class EnterpriseFTPFrontController : Controller
    {
        //
        // GET: /Admin/EnterpriseFTPFront/
        BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
        BLL.FTP_New ftpBLL = new BLL.FTP_New();
        BLL.Common commonBLL = new BLL.Common();
        BLL.PrvUser userBLL = new BLL.PrvUser();
        BLL.HRDept hrDeptBLL = new BLL.HRDept();
        string entityNo = GlobalConstant.ENTITYNO;
        public ActionResult Index(string focusNodeName = "")
        {
            bool isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;

            if (isLogin)
            {
                ViewData["focusNodeName"] = focusNodeName;
                List<Model.FTP_New> ftpList = ftpBLL.GetListByEntityNo(GlobalConstant.ENTITYNO);
                ViewData["isHaveTreeData"] = ftpList.Count == 0 ? false : true;
                return View();
            }
            else
            {

                Response.Write("<script>alert('请先登录');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }
        }

        /// <summary>
        /// 左边栏目列表树
        /// </summary>
        /// <param name="focusNodeName">焦点名</param>
        /// <param name="type">类型</param>
        /// <returns>视图</returns>
        public ActionResult EnterpriseFTPTree(string focusNodeName = "")
        {
            TreeModelList treeModelList = new TreeModelList();

            List<Model.FTP_New> ftpList = ftpBLL.GetListByEntityNo(GlobalConstant.ENTITYNO);

            bool isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;

            if (isLogin)
            {
                string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                if (ftpList.Count > 0)
                {
                    TreeItemModel NoArchiveRootUpload = new TreeItemModel(null)
                    {
                        Id = "",
                        ImageUrl = Url.Content("~/Content/FunctionImages/m_Document.png"),
                        Name = "上传"
                    };
                    treeModelList.Add(NoArchiveRootUpload);
                    List<Model.FTP_New> FtpFirstList = (from m in ftpList
                                                        where m.FParentID == null & m.FIsArchive == "N" & m.FIsUpload == "Y"
                                                        select m).ToList();

                    foreach (Model.FTP_New ftpModel in FtpFirstList)
                    {
                        List<Model.FTP_New> tmpFtpList = (from m in ftpList
                                                          where m.FParentID == ftpModel.FID & m.FIsArchive == "N"
                                                          select m).ToList();

                        TreeItemModel treeParentItemModel = new TreeItemModel(NoArchiveRootUpload)
                        {
                            Id = ftpModel.FID.ToString(),
                            Name = ftpModel.FName
                        };
                        if (tmpFtpList.Count > 0)
                        {
                            GetChildFtpList(tmpFtpList, treeParentItemModel, ftpList);
                        }

                    }

                    TreeItemModel NoArchiveRootDownload = new TreeItemModel(null)
                    {
                        Id = "",
                        ImageUrl = Url.Content("~/Content/FunctionImages/m_Document.png"),
                        Name = "下载"
                    };
                    treeModelList.Add(NoArchiveRootDownload);
                    List<Model.FTP_New> FtpFirstListDownload = (from m in ftpList
                                                                where m.FParentID == null & m.FIsArchive == "N" & m.FIsDownload == "Y"
                                                                select m).ToList();

                    foreach (Model.FTP_New ftpModel in FtpFirstListDownload)
                    {
                        List<Model.FTP_New> tmpFtpList = (from m in ftpList
                                                          where m.FParentID == ftpModel.FID & m.FIsArchive == "N"
                                                          select m).ToList();

                        TreeItemModel treeParentItemModel = new TreeItemModel(NoArchiveRootDownload)
                        {
                            Id = ftpModel.FID.ToString(),
                            Name = ftpModel.FName
                        };
                        if (tmpFtpList.Count > 0)
                        {
                            GetChildFtpList(tmpFtpList, treeParentItemModel, ftpList);
                        }

                    }

                    BLL.FTP ftpbll = new BLL.FTP();
                    if (ftpbll.FIsAllowLookFtpByEmpNo(emplNo, entityNo))
                    {
                        TreeItemModel treeParentItemModelach = new TreeItemModel(null)
                        {
                            Id = "",
                            ImageUrl = Url.Content("~/Content/FunctionImages/m_Document.png"),
                            Name = "归档目录"
                        };
                        treeModelList.Add(treeParentItemModelach);

                        TreeItemModel ArchiveRootUpload = new TreeItemModel(treeParentItemModelach)
                        {
                            Id = "",
                            ImageUrl = Url.Content("~/Content/FunctionImages/m_Document.png"),
                            Name = "上传"
                        };
                        List<Model.FTP_New> FTP_NewFirstListach = (from m in ftpList
                                                                   where m.FParentID == null & m.FIsArchive == "Y" & m.FIsUpload == "Y"
                                                                   select m).ToList();
                        foreach (Model.FTP_New FTP_NewModel in FTP_NewFirstListach)
                        {
                            List<Model.FTP_New> tmpFTP_NewList = (from m in ftpList
                                                                  where m.FParentID == FTP_NewModel.FID & m.FIsArchive == "Y"
                                                                  select m).ToList();

                            TreeItemModel treeParentItemModel = new TreeItemModel(ArchiveRootUpload)
                            {
                                Id = FTP_NewModel.FID.ToString(),
                                Name = FTP_NewModel.FName
                            };
                            treeParentItemModel.Id = treeParentItemModel.Id.Replace("&", "|");
                            if (tmpFTP_NewList.Count > 0)
                            {
                                GetChildFTP_NewListach(tmpFTP_NewList, treeParentItemModel, ftpList);
                            }
                            //   treeModelList.Add(treeParentItemModel);
                        }
                        TreeItemModel ArchiveRootDownload = new TreeItemModel(treeParentItemModelach)
                        {
                            Id = "",
                            ImageUrl = Url.Content("~/Content/FunctionImages/m_Document.png"),
                            Name = "下载"
                        };
                        List<Model.FTP_New> FTP_NewFirstListachDownload = (from m in ftpList
                                                                           where m.FParentID == null & m.FIsArchive == "Y" & m.FIsDownload == "Y"
                                                                           select m).ToList();
                        foreach (Model.FTP_New FTP_NewModel in FTP_NewFirstListachDownload)
                        {
                            List<Model.FTP_New> tmpFTP_NewList = (from m in ftpList
                                                                  where m.FParentID == FTP_NewModel.FID & m.FIsArchive == "Y"
                                                                  select m).ToList();

                            TreeItemModel treeParentItemModel = new TreeItemModel(ArchiveRootDownload)
                            {
                                Id = FTP_NewModel.FID.ToString(),
                                Name = FTP_NewModel.FName
                            };
                            treeParentItemModel.Id = treeParentItemModel.Id.Replace("&", "|");
                            if (tmpFTP_NewList.Count > 0)
                            {
                                GetChildFTP_NewListach(tmpFTP_NewList, treeParentItemModel, ftpList);
                            }
                            //   treeModelList.Add(treeParentItemModel);
                        }
                    }
                }
            }
            ViewData["focusNodeName"] = focusNodeName;
            return PartialView(treeModelList);
        }


        public void GetChildFTP_NewListach(List<Model.FTP_New> FTP_NewChildList, TreeItemModel treeParentItemModel, List<Model.FTP_New> FTP_NewList)
        {
            foreach (Model.FTP_New FTP_NewModel in FTP_NewChildList)
            {
                List<Model.FTP_New> tmpFTP_NewList = (from m in FTP_NewList
                                                      where m.FParentID == FTP_NewModel.FID & m.FIsArchive == "Y"
                                                      select m).ToList();

                TreeItemModel treeChildItemModel = new TreeItemModel(treeParentItemModel)
                {
                    Id = FTP_NewModel.FID.ToString(),
                    Name = FTP_NewModel.FName
                };
                treeChildItemModel.Id = treeChildItemModel.Id.Replace("&", "|");
                if (tmpFTP_NewList.Count > 0)
                {
                    GetChildFTP_NewListach(tmpFTP_NewList, treeChildItemModel, FTP_NewList);
                }
            }
        }
        public void GetChildFtpList(List<Model.FTP_New> ftpChildList, TreeItemModel treeParentItemModel, List<Model.FTP_New> ftpList)
        {
            foreach (Model.FTP_New ftpModel in ftpChildList)
            {
                List<Model.FTP_New> tmpFtpList = (from m in ftpList
                                                  where m.FParentID == ftpModel.FID & m.FIsArchive == "N"
                                                  select m).ToList();

                TreeItemModel treeChildItemModel = new TreeItemModel(treeParentItemModel)
                {
                    Id = ftpModel.FID.ToString(),
                    Name = ftpModel.FName
                };
                if (tmpFtpList.Count > 0)
                {
                    GetChildFtpList(tmpFtpList, treeChildItemModel, ftpList);
                }
            }
        }

        /// <summary>
        /// 修改成有单位的文件大小
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        private string GetstrSize(decimal size)
        {
            string strSize = "0KB";
            if (size == 0)
            {
                strSize = "0B";
            }
            else if (size > 0 && size < 1024)
            {
                string _size = size.ToString();
                strSize = _size.ToString() + "B";
            }
            else if (size > 0 && size < 1048576)
            {
                string _size = ((decimal)size / (decimal)1024).ToString("0.00");
                strSize = _size.ToString() + "KB";
            }
            else if (size >= 1048576 && size < 1073741824)
            {
                string _size = ((decimal)size / (decimal)1048576).ToString("0.00");
                strSize = _size + "MB";
            }
            else
            {
                string _size = ((decimal)size / (decimal)1073741824).ToString("0.00");
                strSize = _size + "GB";
            }
            return strSize;
        }

        public ActionResult EnterpriseFTPList(string FId, int id = 1)
        {

            #region 上传文件相关
            string upload_url = Url.Content("~/Admin/EnterpriseFTPFront/Upload?parentId=" + FId);
            string file_size_limit = "2147483648";
            //string file_types = "*.exe;*.iso;*.rar;*.msi;*.zip;*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.txt;*.jpg;*.gif;*.png";
            //string DesTitle = "上传软件（支持的软件类型exe,iso,rar,msi,zip,doc,docx,xls,xlsx,ppt,txt,jpg,gif,png)";
            string file_types = "*.*";
            string DesTitle = "上传软件（支持所有软件类型)";
            string button_image_url = Url.Content("~/Content/images/Dqypt/scxz03.png");

            ViewData["button_image_url"] = button_image_url;
            ViewData["DesTitle"] = DesTitle;
            ViewData["file_types"] = file_types;
            ViewData["file_size_limit"] = file_size_limit;
            ViewData["upload_url"] = upload_url;
            #endregion


            int pageSize = 12;
            int total = 0;
            string strWhere = " 1=1 ";
            string logId = OperateSession.get(Common.GlobalConstant.PARAM_LOGINID);
            string deptNo = OperateSession.get(Common.GlobalConstant.PARAM_DEPTNO);
            string IsUpload = "N";//是否上传
            string IsAgency = "N";//是否派出机构

            if (!string.IsNullOrEmpty(FId))
            {
                //获取该文件夹的数据
                Model.FTP_New parentFTP = ftpBLL.GetModel(decimal.Parse(FId));

                IsUpload = parentFTP.FIsUpload;//是否上传
                string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                string deptno = "";
                string deptnname = "";
                DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                        {
                            ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                            ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                            deptno = dt.Rows[i]["FDeptNo"].ToString();
                            deptnname = ViewData["DeptName"].ToString();
                            break;
                        }

                    }

                }
                BLL.FTP ftpbll = new BLL.FTP();
                if (!ftpbll.FIsAllowLookFtpByEmpNo(emplNo, entityNo))
                {
                    //无全局下载权限
                    ViewData["isall"] = false;
                }
                else
                {
                    ViewData["isall"] = true;
                }
                //如果是市局
                Model.HRDept mdept = hrDeptBLL.GetModel(entityNo, deptno);
                //是否派出机构
                if (mdept.FIsAgency == "Y")
                {
                    IsAgency = "Y";
                }
                else
                {
                    IsAgency = "N";
                }
                if ((bool)ViewData["isall"])
                {
                    //全部取出包含所有权限

                    //如果是派出机构


                    strWhere += "AND (FParentID ='" + FId + "'  and FType='F' AND NOT EXISTS(SELECT * FROM dbo.t_FTP_New WHERE FParentID ='" + FId + "'  and FType='D'  ) )  or ( FParentID ='" + FId + "'  and FType='D' AND EXISTS(SELECT * FROM dbo.t_FTP_New WHERE FParentID ='" + FId + "' and FType='D'  ))";



                }
                else
                {
                    //如果是上传，派出机构只能看自己部门的文件;如果是下载，任何人都能看
                    if (IsUpload == "Y")
                    {
                        //如果是派出机构
                        if (IsAgency == "Y")
                        {
                            strWhere += " AND ( FDeptNo='" + deptNo + "'and FParentID ='" + FId + "'  and FType='F' AND NOT EXISTS(SELECT * FROM dbo.t_FTP_New WHERE FParentID ='" + FId + "'  and FType='D'  ) )  or ( FParentID ='" + FId + "'  and FType='D' AND EXISTS(SELECT * FROM dbo.t_FTP_New WHERE FParentID ='" + FId + "'  and FType='D' ))";
                        }
                        else
                        {

                            strWhere += "AND( FDeptNo IN (SELECT FDeptNo from dbo.t_HRDept WHERE FIsAgency='N') and FParentID ='" + FId + "'  and FType='F' AND NOT EXISTS(SELECT * FROM dbo.t_FTP_New WHERE FParentID ='" + FId + "'  and FType='D'  ) )  or ( FParentID ='" + FId + "'  and FType='D' AND EXISTS(SELECT * FROM dbo.t_FTP_New WHERE FParentID ='" + FId + "'  and FType='D' ))";

                        }
                    }
                    else
                    {
                        //全部取出只能被下载

                        strWhere += "AND (FParentID ='" + FId + "'  and FType='F' AND NOT EXISTS(SELECT * FROM dbo.t_FTP_New WHERE FParentID ='" + FId + "'  and FType='D'  ) )  or ( FParentID ='" + FId + "'  and FType='D' AND EXISTS(SELECT * FROM dbo.t_FTP_New WHERE FParentID ='" + FId + "'  and FType='D' ))";

                    }
                }




                List<Model.FTP_New> ftpGridList = GetFtpList(FId, strWhere, pageSize, out total, id);
                ftpGridList = ftpGridList.OrderBy(h => h.FID).ToList();
                //生成文件大小字段，精确到B
                foreach (Model.FTP_New ftpGridModel in ftpGridList)
                {
                    ftpGridModel.strSize = GetstrSize(ftpGridModel.FSize);
                }
                var mdl = ftpBLL.GetModelList("FParentID ='" + FId + "'  and FType='D'");
                if (mdl.Count == 0)
                {
                    ViewData["isbottom"] = true;
                }
                else
                {
                    ViewData["isbottom"] = false;
                }
                PagedList<Model.FTP_New> ftpList = new PagedList<Model.FTP_New>(ftpGridList, id, pageSize, total);
                ViewData["parentId"] = FId;
                ViewData["IsUpload"] = IsUpload;
                ViewData["IsAgency"] = IsAgency;
                return PartialView("EnterpriseFTPList", ftpList);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 分页获取文件
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="total"></param>
        /// <param name="isHomePage"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        private List<Model.FTP_New> GetFtpList(string FID, string strWhere, int pageSize, out int total, int pageIndex = 1)
        {
            total = 0;
            List<Model.FTP_New> ftpList = new List<Model.FTP_New>();
            string fieldOrder = "FID ";
            string fields = "*";
            string entityNo = Common.GlobalConstant.ENTITYNO;
            string tableName = "v_FTP";
            if (FID != null)
            {
                //   strWhere += " AND( ( FParentID ='" + FID + "'  and FType='D' AND EXISTS(SELECT * FROM dbo.t_FTP_New WHERE FParentID ='" + FID + "'  and FType='D'  )) OR ( FParentID ='" + FID + "'  and FType='F' AND NOT EXISTS(SELECT * FROM dbo.t_FTP_New WHERE FParentID ='" + FID + "'  and FType='D'  ) )) ";
            }
            else
            {
                // strWhere += " AND FEntityNo='" + entityNo + "' ";
            }

            DataSet ds = commonBLL.GetListByPage(tableName, fields, pageSize, pageIndex, strWhere, fieldOrder, 1, out total);
            ftpList = ftpBLL.DataTableToList(ds.Tables[0]);

            return ftpList;
        }

        #region 上传文件相关

        public ActionResult Upload(string parentId)
        {
            Response.Expires = 0;
            bool isSuccess = true;
            string errorString = "";

            System.Web.HttpFileCollectionBase uploadFiles = Request.Files;
            HttpPostedFileBase theFile;
            if (uploadFiles.Count > 0)
            {
                for (int i = 0; i < uploadFiles.Count; i++)
                {
                    theFile = uploadFiles[i];
                    if (theFile != null)
                    {

                        //判断是否存在当前文件名
                        if (ftpBLL.ExistSameNameWithNewName(decimal.Parse(parentId), theFile.FileName))
                        {
                            isSuccess = false;
                            errorString = "此栏目中已存在下列文件名：" + theFile.FileName + "，不能上传此文件。";
                        }

                        if (isSuccess)
                        {
                            //文件后缀名
                            string _backname = theFile.FileName.Substring(theFile.FileName.LastIndexOf('.') + 1);
                            //公司编号
                            string _entityNo = GlobalConstant.ENTITYNO;
                            //目录编号
                            decimal _parentId = decimal.Parse(parentId);
                            //目标文件夹(绝对路径)
                            string dest_dir = System.Configuration.ConfigurationManager.AppSettings["scxzFilePath"];
                            //获取上级栏目路
                            dest_dir += GetPathByPid(_parentId);

                            ////服务器文件名
                            //string _SvrFileName = GenerateUtil.GenerateStringId();
                            ////软件大小
                            //decimal size1 = theFile.ContentLength / 1048576;
                            //decimal size2 = theFile.ContentLength % 1048576;
                            //decimal _size = decimal.Parse(size1.ToString() + "." + size2.ToString().Substring(0, 3));
                            //原来文件名
                            string _oldfilename = theFile.FileName.Substring(theFile.FileName.LastIndexOf('\\') + 1);

                            string uploadoffiepath = dest_dir;//上传文件的路径
                            if (!Directory.Exists(uploadoffiepath))//如果不存在就创建
                            {
                                Directory.CreateDirectory(uploadoffiepath);
                            }

                            try
                            {
                                theFile.SaveAs(uploadoffiepath + _oldfilename);
                                isSuccess = true;
                            }
                            catch (Exception ex)
                            {
                                isSuccess = false;
                                errorString = ex.ToString();
                            }
                            //如果文件上传成功，则保存数据
                            Model.FTP_New ftpModel = new Model.FTP_New();
                            if (isSuccess)
                            {
                                try
                                {
                                    Model.FTP_New oldFTP_NewModel = ftpBLL.GetModel(decimal.Parse(parentId));
                                    ftpModel.FParentID = decimal.Parse(parentId);
                                    ftpModel.FName = _oldfilename;
                                    ftpModel.FSuffixName = _backname;
                                    ftpModel.FType = "F";
                                    ftpModel.FSize = theFile.ContentLength;
                                    ftpModel.FLogID = OperateSession.get(Common.GlobalConstant.PARAM_LOGINID);
                                    ftpModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                                    ftpModel.FIsArchive = oldFTP_NewModel.FIsArchive;
                                    ftpModel.FIsDownload = oldFTP_NewModel.FIsDownload;
                                    ftpModel.FIsUpload = oldFTP_NewModel.FIsUpload;

                                    //保存数据
                                    ftpBLL.AddFTP_New(ftpModel);
                                    isSuccess = true;
                                }
                                catch (Exception ex)
                                {
                                    isSuccess = false;
                                    errorString = ex.ToString();
                                }
                            }
                            //如果不成功，则删除文件
                            if (!isSuccess)
                            {
                                if (System.IO.File.Exists(uploadoffiepath + _oldfilename))
                                {
                                    System.IO.File.Delete(uploadoffiepath + _oldfilename);
                                }
                            }
                        }
                        if (isSuccess)
                        {
                            Response.Write("successed|" + parentId);
                        }
                        else
                        {
                            Response.Write("error|" + parentId + "|" + errorString);
                        }
                        Response.Flush();
                        Response.End();


                    }
                }
            }

            return null;
        }

        #endregion

        #region 删除
        public string DelFile(string strIds)
        {
            bool isSuccess = true;
            string returnValue = "";

            //获取id
            strIds = strIds.Trim(',');
            string strWhere = " FID IN (" + strIds + ") ";
            List<Model.FTP_New> ftpList = ftpBLL.GetModelList(strWhere);

            foreach (Model.FTP_New ftpModel in ftpList)
            {
                //先删除文件
                if (isSuccess)
                {
                    try
                    {
                        string srvPath = System.Configuration.ConfigurationManager.AppSettings["scxzFilePath"];
                        if (ftpModel.FParentID != null)
                        {
                            srvPath += GetPathByPid(ftpModel.FParentID.Value);
                        }
                        if (System.IO.File.Exists(srvPath + ftpModel.FName))
                        {
                            System.IO.File.Delete(srvPath + ftpModel.FName);
                        }
                        isSuccess = true;
                    }
                    catch
                    {
                        isSuccess = false;
                        returnValue = "error";
                    }
                }
                //如果文件删除成功，再删除数据
                try
                {
                    if (isSuccess)
                    {
                        ftpBLL.deleteFTP_New(ftpModel.FID);
                        returnValue = "success";
                    }
                }
                catch
                {
                    returnValue = "error";
                }
            }


            return returnValue;

        }

        #endregion

        #region 下载文件

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult Downloadold(string ids)
        {
            Model.FTP_New ftpModel = ftpBLL.GetModel(decimal.Parse(ids));

            string scxzFilePath = System.Configuration.ConfigurationManager.AppSettings["scxzFilePath"];//上传下载文件夹路径
            string strZipTopDirectoryPath = scxzFilePath;//文件路径
            if (ftpModel.FParentID != null)
            {
                strZipTopDirectoryPath += GetPathByPid(ftpModel.FParentID.Value);
            }

            string strFilePath = strZipTopDirectoryPath + ftpModel.FName;

            return new Common.FileResult() { FilePaht = strFilePath, FileName = ftpModel.FName };
        }
        public string ExistsFile(string strIds)
        {
            string[] ids = strIds.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (ids.Length == 1)
            {
                string strWhere = " FID = '" + ids + "' ";
                DataTable ftpList = ftpBLL.GetAllFileCteByDirOrFileFid(strWhere);
                if (ftpList.Rows.Count == 0)
                {
                    return "当前选择目录中不存在文件";

                }
                else
                {
                    return "ok";
                }
            }
            else
            {

                string strWhere = " FID IN (" + strIds + ") ";
                DataTable ftpList = ftpBLL.GetAllFileCteByDirOrFileFid(strWhere);
                if (ftpList.Rows.Count == 0)
                {
                    return "当前选择目录中不存在文件";

                }
                else
                {
                    return "ok";
                }
            }

        }
        public ActionResult Download(string ids)
        {
            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            string deptno = "";

            DataSet ds2 = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
            if (ds2.Tables[0].Rows.Count > 0)
            {
                DataTable dt2 = ds2.Tables[0];
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    if (dt2.Rows[i]["FIsMainPosition"].ToString() == "Y")
                    {
                        ViewData["EmpName"] = dt2.Rows[i]["FEmpName"].ToString();
                        ViewData["DeptName"] = dt2.Rows[i]["FDeptName"].ToString();
                        deptno = dt2.Rows[i]["FDeptNo"].ToString();
                        //  deptnname = ViewData["DeptName"].ToString();
                        break;
                    }

                }

            }
            bool isall;
            BLL.FTP ftpbll = new BLL.FTP();
            if (!ftpbll.FIsAllowLookFtpByEmpNo(emplNo, entityNo))
            {
                //无全局下载权限
                isall = false;
            }
            else
            {
                isall = true;
            }
            string IsAgency;
            Model.HRDept mdept = hrDeptBLL.GetModel(entityNo, deptno);
            //是否派出机构
            if (mdept.FIsAgency == "Y")
            {
                IsAgency = "Y";
            }
            else
            {
                IsAgency = "N";
            }
            string strWhere = " FID = '" + ids + "' ";
            string strWhere2 = "";
            if (isall)
            {

                //获取id

            }
            else
            {

                if (IsAgency == "Y")
                {
                    strWhere2 = "(FDeptNo='" + deptno + "') or FIsDownload='Y'";
                }
                else
                {

                    strWhere2 = "(FDeptNo IN (SELECT FDeptNo from dbo.t_HRDept WHERE FIsAgency='N')) or FIsDownload='Y'";

                }
            }
            DataTable ftpListorg = ftpBLL.GetAllFileCteByDirOrFileFid(strWhere);
            if (ftpListorg.Rows.Count == 0)
            {
                string strZipPath2 = "C:/Windows/Temp/EnterpriseFTP" + DateTime.Now.ToString("yyyyMMddHHmm") + Common.GenerateUtil.GenerateStringId() + ".zip";//zip文件路径
                Zip.CreateFileZipEmpty(strZipPath2);
                return new Common.FileResult() { FilePaht = strZipPath2, FileName = "下载文件.zip" };
            }
            DataRow[] dr = ftpListorg.Select(strWhere2);
            if (dr.Count() == 0)
            {

                string strZipPath2 = "C:/Windows/Temp/EnterpriseFTP" + DateTime.Now.ToString("yyyyMMddHHmm") + Common.GenerateUtil.GenerateStringId() + ".zip";//zip文件路径
                Zip.CreateFileZipEmpty(strZipPath2);
                return new Common.FileResult() { FilePaht = strZipPath2, FileName = "下载文件.zip" };
            }
            DataTable ftpList = ftpListorg.Select(strWhere2).CopyToDataTable();


            string scxzFilePath = System.Configuration.ConfigurationManager.AppSettings["scxzFilePath"];//上传下载文件夹路径
            string strZipPath = "C:/Windows/Temp/EnterpriseFTP" + DateTime.Now.ToString("yyyyMMddHHmm") + Common.GenerateUtil.GenerateStringId() + ".zip";//zip文件路径


            if (ftpList.Rows.Count == 0)
            {
                Zip.CreateFileZipEmpty(strZipPath);
                return new Common.FileResult() { FilePaht = strZipPath, FileName = "下载文件.zip" };
            }

            DataTable dt = ftpBLL.GetListPre(decimal.Parse(ftpList.Rows[0]["FParentID"].ToString()));
            dt.DefaultView.Sort = "idLevel asc";
            dt = dt.DefaultView.ToTable();
            string AllparentPath = string.Join("/", dt.AsEnumerable().Select(h => h.Field<string>("FName").ToString()));
            int a = dt.Rows.Count;

            if (ftpList.Rows.Count == 1)
            {
                DataRow ftpModel = ftpList.Rows[0];
                string strZipTopDirectoryPath = scxzFilePath;//文件路径
                if (ftpModel["FParentID"] != null)
                {
                    strZipTopDirectoryPath += GetPathByPid(decimal.Parse(ftpModel["FParentID"].ToString()));
                }

                string strFilePath = strZipTopDirectoryPath + ftpModel["FName"].ToString();


                HttpContext.Response.Write("<script languge='javascript'> parent.hidelp(); window.location.href='" + Url.Action("DownloadFileResult", "EnterpriseFTPFront", new { strPath = strFilePath, Pahtout = ftpModel["FName"].ToString() }) + "'</script>");
                HttpContext.Response.Flush();
                Response.End();
                return null;
               // return new Common.FileResult() { FilePaht = strFilePath, FileName = ftpModel["FName"].ToString() };
            }
            else
            {
                //需要下载的文件路径
                List<DownLoadModel> downLoadList = new List<DownLoadModel>();
                foreach (DataRow ftpModel in ftpList.Rows)
                {
                    string strZipTopDirectoryPath = scxzFilePath;//需要压缩文件的路径
                    if (ftpModel["FParentID"] != null)
                    {
                        strZipTopDirectoryPath += GetPathByPid(decimal.Parse(ftpModel["FParentID"].ToString()));
                    }
                    DownLoadModel downloadModel = new DownLoadModel();
                    downloadModel.path = strZipTopDirectoryPath;
                    downloadModel.file = ftpModel["FName"].ToString();
                    downloadModel.deptname = GetPathByPid(decimal.Parse(ftpModel["FParentID"].ToString()));
                    downLoadList.Add(downloadModel);

                }
                // Zip.CreateFileZip(strZipPath, downLoadList);
                Zip.CreateFileZip3(strZipPath, AllparentPath, downLoadList);

                HttpContext.Response.Write("<script languge='javascript'> parent.hidelp(); window.location.href='" + Url.Action("DownloadFileResult", "EnterpriseFTPFront", new { strPath = strZipPath, Pahtout = "下载文件.zip" }) + "'</script>");
                HttpContext.Response.Flush();
                Response.End();
                return null;


              //  return new Common.FileResult() { FilePaht = strZipPath, FileName = "下载文件.zip" };
            }
        }
        /// <summary>
        /// 批量下载文件
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DownloadList(string ids)
        {

            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            string deptno = "";

            DataSet ds2 = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
            if (ds2.Tables[0].Rows.Count > 0)
            {
                DataTable dt2 = ds2.Tables[0];
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    if (dt2.Rows[i]["FIsMainPosition"].ToString() == "Y")
                    {
                        ViewData["EmpName"] = dt2.Rows[i]["FEmpName"].ToString();
                        ViewData["DeptName"] = dt2.Rows[i]["FDeptName"].ToString();
                        deptno = dt2.Rows[i]["FDeptNo"].ToString();
                        //  deptnname = ViewData["DeptName"].ToString();
                        break;
                    }

                }

            }
            bool isall;
            BLL.FTP ftpbll = new BLL.FTP();
            if (!ftpbll.FIsAllowLookFtpByEmpNo(emplNo, entityNo))
            {
                //无全局下载权限
                isall = false;
            }
            else
            {
                isall = true;
            }
            string IsAgency;
            Model.HRDept mdept = hrDeptBLL.GetModel(entityNo, deptno);
            //是否派出机构
            if (mdept.FIsAgency == "Y")
            {
                IsAgency = "Y";
            }
            else
            {
                IsAgency = "N";
            }
            string strWhere = " FID IN (" + ids + ") ";
            string strWhere2 = "";
            if (isall)
            {

                //获取id

            }
            else
            {
                if (IsAgency == "Y")
                {
                    strWhere2 = "(FDeptNo='" + deptno + "') or FIsDownload='Y'";
                }
                else
                {

                    strWhere2 = "(FDeptNo IN (SELECT FDeptNo from dbo.t_HRDept WHERE FIsAgency='N')) or FIsDownload='Y'";

                }
            }
            //获取id

            DataTable ftpListorg = ftpBLL.GetAllFileCteByDirOrFileFid(strWhere);
            if (ftpListorg.Rows.Count == 0)
            {
                string strZipPath2 = "C:/Windows/Temp/EnterpriseFTP" + DateTime.Now.ToString("yyyyMMddHHmm") + Common.GenerateUtil.GenerateStringId() + ".zip";//zip文件路径
                Zip.CreateFileZipEmpty(strZipPath2);
                return new Common.FileResult() { FilePaht = strZipPath2, FileName = "下载文件.zip" };
            }
            DataRow[] dr = ftpListorg.Select(strWhere2);
            if (dr.Count() == 0)
            {

                string strZipPath2 = "C:/Windows/Temp/EnterpriseFTP" + DateTime.Now.ToString("yyyyMMddHHmm") + Common.GenerateUtil.GenerateStringId() + ".zip";//zip文件路径
                Zip.CreateFileZipEmpty(strZipPath2);
                return new Common.FileResult() { FilePaht = strZipPath2, FileName = "下载文件.zip" };
            }
            DataTable ftpList = ftpListorg.Select(strWhere2).CopyToDataTable();



            if (ftpList.Rows.Count == 0)
            {
                string strZipPath2 = "C:/Windows/Temp/EnterpriseFTP" + DateTime.Now.ToString("yyyyMMddHHmm") + Common.GenerateUtil.GenerateStringId() + ".zip";//zip文件路径
                Zip.CreateFileZipEmpty(strZipPath2);
                return new Common.FileResult() { FilePaht = strZipPath2, FileName = "下载文件.zip" };
            }

            DataTable dt = ftpBLL.GetListPre(decimal.Parse(ftpList.Rows[0]["FParentID"].ToString()));
            dt.DefaultView.Sort = "idLevel asc";
            dt = dt.DefaultView.ToTable();
            string AllparentPath = string.Join("/", dt.AsEnumerable().Select(h => h.Field<string>("FName").ToString()));
            int a = dt.Rows.Count;
            string scxzFilePath = System.Configuration.ConfigurationManager.AppSettings["scxzFilePath"];//上传下载文件夹路径
            string strZipPath = "C:/Windows/Temp/EnterpriseFTP" + DateTime.Now.ToString("yyyyMMddHHmm") + Common.GenerateUtil.GenerateStringId() + ".zip";//zip文件路径

            //需要下载的文件路径
            List<DownLoadModel> downLoadList = new List<DownLoadModel>();
            foreach (DataRow ftpModel in ftpList.Rows)
            {
                string strZipTopDirectoryPath = scxzFilePath;//需要压缩文件的路径
                if (ftpModel["FParentID"] != null)
                {
                    strZipTopDirectoryPath += GetPathByPid(decimal.Parse(ftpModel["FParentID"].ToString()));
                }
                DownLoadModel downloadModel = new DownLoadModel();
                downloadModel.path = strZipTopDirectoryPath;
                downloadModel.file = ftpModel["FName"].ToString();
                downloadModel.deptname = GetPathByPid(decimal.Parse(ftpModel["FParentID"].ToString()));
                downLoadList.Add(downloadModel);

            }
            // Zip.CreateFileZip(strZipPath, downLoadList);
            Zip.CreateFileZip3(strZipPath, AllparentPath, downLoadList);



        // return new Common.FileResult() { FilePaht = strZipPath, FileName = "下载文件.zip" };
            HttpContext.Response.Write("<script languge='javascript'> parent.hidelp(); window.location.href='" + Url.Action("DownloadFileResult", "EnterpriseFTPFront", new { strPath = strZipPath, Pahtout = "下载文件.zip" }) + "'</script>");
            HttpContext.Response.Flush();
            Response.End();
            return null;
        }
        public ActionResult DownloadFileResult(string strPath, string Pahtout)
        {
            return new Common.FileResult() { FilePaht = strPath, FileName = Pahtout };

        }
        #endregion

        #region 复制移动

        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="strIds"></param>
        /// <param name="destIdHtml"></param>
        /// <returns></returns>
        public string MoveFile(string strIds, string destIdHtml)
        {
            string returnValue = "";
            bool isSuccess = true;
            string scxzFilePath = System.Configuration.ConfigurationManager.AppSettings["scxzFilePath"];//上传下载文件夹路径

            //获取需要移动的文件
            string strWhere = " FID IN (" + strIds + ") ";
            List<Model.FTP_New> ftpList = ftpBLL.GetModelList(strWhere);

            //新的文件夹
            Model.FTP_New newFtpModel = new Model.FTP_New();
            if (destIdHtml != "")
            {
                List<Models.CommonValueModel> newFtpList = JsonConvert.DeserializeObject<List<Models.CommonValueModel>>(destIdHtml);
                if (newFtpList.Count > 0)
                {
                    if (string.IsNullOrEmpty(newFtpList[0].Value))
                    {
                      //  returnValue = "error|" + "虚拟节点不能移动";
                        returnValue = "notend";
                        return returnValue;
                    } 
                    else
                    {
                    }
                    newFtpModel.FID = decimal.Parse(newFtpList[0].Value);
                    newFtpModel.FName = newFtpList[0].Text;
                }
            }
            List<Model.FTP_New> ftpListExist = ftpBLL.GetModelList("FParentID='" + newFtpModel.FID + "' and FType='D'");
            if (ftpListExist.Count > 0)
            {
                returnValue = "notend";
                return returnValue;
            }


            string oldFilePath = "";//原来文件夹路径
            string newFilePath = "";//新文件夹路径


            if (ftpList.Count > 0)
            {
                //判断是否有重复的文件名
                if (ftpBLL.ExistSameName(newFtpModel.FID, strIds))
                {
                    returnValue = "same";
                    return returnValue;
                }
                else
                {

                    newFilePath = scxzFilePath + GetPathByPid(newFtpModel.FID);

                    foreach (Model.FTP_New ftpModel in ftpList)
                    {
                        oldFilePath = "";//清除旧文件路径
                        string fileName = ftpModel.FName;

                        if (ftpModel.FParentID != newFtpModel.FID)//如果新文件夹路径和老的一致，则不进行移动操作
                        {
                            //先移动文件
                            try
                            {
                                if (isSuccess)
                                {
                                    oldFilePath = scxzFilePath + GetPathByPid(ftpModel.FParentID.Value);

                                    MoveFileFunc(oldFilePath + fileName, newFilePath + fileName);
                                }
                            }
                            catch (Exception ex)
                            {
                                isSuccess = false;
                                returnValue = "error|" + ex.ToString();
                                return returnValue;
                            }
                            //如果移动成功，再操作数据库
                            try
                            {
                                if (isSuccess)
                                {
                                    decimal FID = ftpModel.FID;
                                    decimal newParentID = newFtpModel.FID;
                                    ftpBLL.moveFTP_NewFile(FID, newParentID);
                                    returnValue = "ok";
                                }
                            }
                            catch (Exception ex)
                            {
                                isSuccess = false;
                                returnValue = "error|" + ex.ToString();
                            }

                            //如果数据移动失败，则把原来的文件还原回去
                            if (!isSuccess)
                            {
                                if (System.IO.File.Exists(newFilePath + fileName))
                                {
                                    MoveFileFunc(newFilePath + fileName, oldFilePath + fileName);
                                }
                            }

                        }
                    }
                }
            }



            return returnValue;
        }


        /// <summary>
        /// 复制
        /// </summary>
        /// <param name="strIds"></param>
        /// <param name="destIdHtml"></param>
        /// <returns></returns>
        public string CopyFile(string strIds, string destIdHtml)
        {
            string returnValue = "";
            bool isSuccess = true;
            string scxzFilePath = System.Configuration.ConfigurationManager.AppSettings["scxzFilePath"];//上传下载文件夹路径

            //获取需要复制的文件
            string strWhere = " FID IN (" + strIds + ") ";
            List<Model.FTP_New> ftpList = ftpBLL.GetModelList(strWhere);

            //新的文件夹
            Model.FTP_New newFtpModel = new Model.FTP_New();
            if (destIdHtml != "")
            {
                List<Models.CommonValueModel> newFtpList = JsonConvert.DeserializeObject<List<Models.CommonValueModel>>(destIdHtml);
                if (newFtpList.Count > 0)
                {
                    if (string.IsNullOrEmpty(newFtpList[0].Value))
                    {

                        //returnValue = "error|" + "虚拟节点不能复制";
                        returnValue = "notend";
                        return returnValue;
                    } 
                    newFtpModel.FID = decimal.Parse(newFtpList[0].Value);
                    newFtpModel.FName = newFtpList[0].Text;
                }
            }
            List<Model.FTP_New> ftpListExist = ftpBLL.GetModelList("FParentID='" + newFtpModel.FID + "' and FType='D'");
            if (ftpListExist.Count > 0)
            {
                returnValue = "notend";
                return returnValue;
            }
            string oldFilePath = "";//原来文件夹路径
            string newFilePath = "";//新文件夹路径
            if (ftpList.Count > 0)
            {
                //判断是否有重复的文件名
                if (ftpBLL.ExistSameName(newFtpModel.FID, strIds))
                {
                    returnValue = "same";
                    return returnValue;
                }
                else
                {
                    newFilePath = scxzFilePath + GetPathByPid(newFtpModel.FID);

                    foreach (Model.FTP_New ftpModel in ftpList)
                    {
                        oldFilePath = "";//清除旧文件路径

                        string fileName = ftpModel.FName;
                        if (ftpModel.FParentID != newFtpModel.FID)//如果新文件夹路径和老的一致，则不进行复制操作
                        {
                            //先复制文件
                            try
                            {
                                if (isSuccess)
                                {
                                    oldFilePath = scxzFilePath + GetPathByPid(ftpModel.FParentID.Value);

                                    CopyFileFunc(oldFilePath + fileName, newFilePath + fileName);
                                }
                            }
                            catch (Exception ex)
                            {
                                isSuccess = false;
                                returnValue = "error|" + ex.ToString();
                            }
                            //如果复制成功，再操作数据库
                            try
                            {
                                if (isSuccess)
                                {
                                    Model.FTP_New CopyFtpModel = ftpModel;
                                    CopyFtpModel.FParentID = newFtpModel.FID;
                                    CopyFtpModel.FLogID = OperateSession.get(Common.GlobalConstant.PARAM_LOGINID);
                                    ftpBLL.AddFTP_New(CopyFtpModel);
                                    returnValue = "ok";
                                }
                            }
                            catch (Exception ex)
                            {
                                isSuccess = false;
                                returnValue = "error|" + ex.ToString();
                                return returnValue;
                            }

                            //如果数据复制失败，则删除已复制文件
                            if (!isSuccess)
                            {
                                if (System.IO.File.Exists(newFilePath + fileName))
                                {
                                    System.IO.File.Delete(newFilePath + fileName);
                                }
                            }


                        }
                    }
                }
            }



            return returnValue;
        }

        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="destPath"></param>
        /// <returns></returns>
        private bool MoveFileFunc(string sourcePath, string destPath)
        {
            try
            {
                if (System.IO.File.Exists(destPath))
                    System.IO.File.Delete(destPath);
                FileInfo fi = new FileInfo(destPath);
                string dir = fi.DirectoryName;
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                System.IO.File.Move(sourcePath, destPath);

                if (System.IO.File.Exists(sourcePath))
                    System.IO.File.Delete(sourcePath);

                return true;

            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="destPath"></param>
        /// <returns></returns>
        private bool CopyFileFunc(string sourcePath, string destPath)
        {
            try
            {
                FileInfo fi = new FileInfo(destPath);
                string dir = fi.DirectoryName;
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                System.IO.File.Copy(sourcePath, destPath, true);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region 重命名

        public ActionResult EnterpriseRename(string FId)
        {
            Model.FTP_New ftpModel = ftpBLL.GetModel(decimal.Parse(FId));
            ftpModel.strName = ftpModel.FName.Substring(0, ftpModel.FName.LastIndexOf('.'));
            return View(ftpModel);
        }

        /// <summary>
        /// 重命名
        /// </summary>
        /// <param name="FId"></param>
        /// <param name="FName"></param>
        /// <returns></returns>
        public string Rename(string FId, string FName)
        {
            string returnValue = "";
            bool isSuccess = true;
            string scxzFilePath = System.Configuration.ConfigurationManager.AppSettings["scxzFilePath"];//上传下载文件夹路径
            Model.FTP_New ftpModel = new Model.FTP_New();

            string oldFileName = "";
            string newFileName = "";

            //获取当前文件的数据
            ftpModel = ftpBLL.GetModel(decimal.Parse(FId));

            //判断本文件夹内是否存在新文件名(考虑ftpModel.FParentID为null)
            if (ftpModel.FParentID == null)
            {
                if (ftpBLL.ExistSameNameWithNewNameWhenNull(FName + "." + ftpModel.FSuffixName))
                {
                    returnValue = "same";
                    isSuccess = false;
                }
            }
            else
            {
                if (ftpBLL.ExistSameNameWithNewName(ftpModel.FParentID.Value, FName + "." + ftpModel.FSuffixName))
                {
                    returnValue = "same";
                    isSuccess = false;
                }
            }



            //先修改物理文件名
            try
            {
                if (isSuccess)
                {
                    string path = scxzFilePath + GetPathByPid(ftpModel.FParentID.Value);
                    oldFileName = path + ftpModel.FName;
                    newFileName = path + FName + "." + ftpModel.FSuffixName;
                    MoveFileFunc(oldFileName, newFileName);
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
                returnValue = "error|" + ex.ToString();
            }

            try
            {
                if (isSuccess)
                {
                    //再更新数据库
                    ftpBLL.renameFTP_NewFile(decimal.Parse(FId), FName + "." + ftpModel.FSuffixName);
                    returnValue = "ok";
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
                returnValue = "error|" + ex.ToString();
            }

            //如果数据库更新失败，则还原为原来的文件名
            if (!isSuccess)
            {
                MoveFileFunc(newFileName, oldFileName);
            }
            return returnValue;
        }


        #endregion

        /// <summary>
        /// 根据父级id获取父级栏目路径
        /// </summary>
        /// <param name="pId"></param>
        /// <returns></returns>
        private string GetPathByPid(decimal pId)
        {
            DataTable dtPreFTP = ftpBLL.GetListPre(pId);
            string strPreFTP = "";
            foreach (DataRow row in dtPreFTP.Rows)
            {
                strPreFTP += row["FName"].ToString() + "\\";
            }
            return strPreFTP;
        }
    }
}
